package band.wukong.practice.mq.activemq.hello.topic;

import band.wukong.practice.mq.activemq.hello.MQServerConst;
import org.apache.activemq.ActiveMQConnectionFactory;

import javax.jms.*;

/**
 * @author wukong(wukonggg@139.com)
 */
public class TopicPublisher {

    public static void main(String[] args) throws JMSException, InterruptedException {
        // ConnectionFactory ：连接工厂，JMS 用它创建连接
        //61616是ActiveMQ默认端口
        ConnectionFactory connectionFactory = new ActiveMQConnectionFactory(
                MQServerConst.ADMIN_NAME,
                MQServerConst.ADMIN_PASSWD,
                MQServerConst.BROKER_URL);

        // Connection ：JMS 客户端到JMS Provider 的连接
        Connection connection = connectionFactory.createConnection();

        connection.start();

        // Session： 一个发送或接收消息的线程
        Session session = connection.createSession(true, Session.AUTO_ACKNOWLEDGE);

        // Destination ：消息的目的地;消息发送给谁.
        Destination destination = session.createTopic(MQServerConst.TOPIC_0);

        // MessageProducer：消息发送者
        MessageProducer producer = session.createProducer(destination);

        // 设置不持久化，可以更改
        producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);

        for (int i = 0; i < 5; i++) {
            //创建文本消息
            TextMessage message = session.createTextMessage("hello.I am producer, this is a test message" + i);
            //发送消息
            producer.send(message);

            Thread.sleep(500);
        }

        session.commit();
        session.close();
        connection.close();
    }
}
